package management_system;

import java.util.*;

public class StudentManager {
    private List<Student> students = new ArrayList<>();
    private Map<String, Course> courseMap = new HashMap<>();

    public StudentManager() {
        courseMap.put("math",    new Course("M101", "高等数学", 4));
        courseMap.put("english", new Course("E101", "大学英语", 3));
        courseMap.put("java",    new Course("J101", "Java程序设计", 3));
    }
    public void addStudent(Student s) { students.add(s); }

    /* 原接口：异常返回 null，不加入成绩 */
    public void addScoreToStudent(String studentId, String courseKey, double score) {
        Score sc = createScore(studentId, courseKey, score);
        if (sc != null) {
            Student stu = findStudentById(studentId);
            if (stu != null) stu.addScore(sc);
        }
    }

    /* 内部工厂：异常返回 null */
    public Score createScore(String studentId, String courseKey, double score) {
        Student stu = findStudentById(studentId);
        if (stu == null) { System.out.println("未找到学号 " + studentId); return null; }
        Course course = courseMap.get(courseKey.toLowerCase());
        if (course == null) { System.out.println("未找到课程 " + courseKey); return null; }
        try {
            return new Score(course, score);
        } catch (InvalidScoreException e) {
            System.out.println(studentId + "学号成绩异常：" + e.getMessage());
            return null;
        }
    }
    public Student findStudentById(String id) {
        for (Student s : students) if (s.getId().equals(id)) return s;
        return null;
    }
    public List<Student> getStudents() { return students; }
}